package org.example.edusmart.controller.UserInfo;

import jakarta.servlet.http.HttpServletRequest;
import org.example.edusmart.request.login.ChangePasswordPojo;
import org.example.edusmart.service.UserService;
import org.example.edusmart.utils.GetTokenInfo;
import org.example.edusmart.utils.Result;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Objects;

@RequestMapping("/userInfo")
@RestController
public class ChangePasswordController {
    @Autowired
    private UserService userService;

    @Autowired
    private GetTokenInfo getTokenInfo;

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;
    /**
     * 登录后忘记密码
     * @param user 前端入参
     * @param request 请求头，token所在位置
     * @return 状态码
     */
    @PostMapping("/changePassword/")
    @PreAuthorize("hasAuthority('public_permission')") //指明有公共权限的才能访问
    public Result alterPassword(HttpServletRequest request, @NotNull @RequestBody ChangePasswordPojo user){
        //获取用户ID
        String userId = getTokenInfo.getUserIdByJwt(request);
        if (Objects.isNull(userId)) {
            return new Result(404,"账号不存在");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return new Result(404, "两次密码输入不一致");
        }
        if (user.getCode().isEmpty()) {
            return new Result(404, "请输入验证码");
        }
        //替换密码，把新密码加密
        HashMap<String, Object> insertData = new HashMap<>() {{
            put("email", user.getEmail());
            put("newPassword",bCryptPasswordEncoder.encode(user.getNewPassword()));
        }};
        userService.changePassword(insertData);
        return new Result(200,"修改成功");
    }
}
